package bb.lanxing.fragment.sport;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.SwitchPreference;
import android.provider.Settings;
import android.widget.Toast;

import com.lzf.easyfloat.permission.PermissionUtils;
import com.lzf.easyfloat.permission.rom.MiuiUtils;

import bb.lanxing.R;
import bb.lanxing.manager.RemoteServiceManager;
import bb.lanxing.fragment.base.BasePreferenceFragment;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.manager.SystemSensorManager;
import bb.lanxing.util.MessageUtil;
import bb.lanxing.util.RomUtil;
import bb.lanxing.util.StartInBackgroundPermissionUtil;
import bb.lanxing.view.BiciAlertDialogBuilder;

public class SettingMoreFragment extends BasePreferenceFragment implements Preference.OnPreferenceChangeListener {
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        migrateSettings();
        getPreferenceManager().setSharedPreferencesName(RemoteSharedPreference.PREFERENCE_FILE_NAME);
        addPreferencesFromResource(R.xml.fragment_setting_more);
        ListPreference listPreference = (ListPreference) findPreference(SPConstant.KEY_ALTITUDE_SOURCE_V2);
        listPreference.setOnPreferenceChangeListener(this);
        if (!SystemSensorManager.getInstance().hasPressureSensor(getContext())) {
            listPreference.setEntries(new CharSequence[]{listPreference.getEntries()[0]});
            listPreference.setEntryValues(new CharSequence[]{listPreference.getEntryValues()[0]});
        }
        int findIndexOfValue = listPreference.findIndexOfValue(String.valueOf(RemoteSharedPreference.getInstance().getAltitudeSource()));
        listPreference.setSummary(findIndexOfValue >= 0 ? listPreference.getEntries()[findIndexOfValue] : null);

        EditTextPreference editTextPreference = (EditTextPreference) findPreference(SPConstant.KEY_ALTITUDE_ADJUST_VALUE_V2);
        editTextPreference.setSummary(String.valueOf(RemoteSharedPreference.getInstance().getAltitudeAdjustValue()));
        editTextPreference.setOnPreferenceChangeListener(this);

        SwitchPreference switchPreference = (SwitchPreference) findPreference(SPConstant.KEY_SPORT_MESSAGE_ENABLE);
        switchPreference.setDefaultValue(RemoteSharedPreference.getInstance().getBoolean(SPConstant.KEY_SPORT_MESSAGE_ENABLE, false));
        switchPreference.setOnPreferenceChangeListener(this);

        SwitchPreference switchPreference2 = (SwitchPreference) findPreference(SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE);
        switchPreference2.setDefaultValue(RemoteSharedPreference.getInstance().isFloatPipEnable());
        switchPreference2.setChecked(RemoteSharedPreference.getInstance().isFloatPipEnable());
        switchPreference2.setOnPreferenceChangeListener(this);

        EditTextPreference editTextPreference2 = (EditTextPreference) findPreference(SPConstant.KEY_LATLNT_SOURCE);
        editTextPreference2.setSummary(SharedManager.getInstance().getLatlngValue());
        editTextPreference2.setOnPreferenceChangeListener(this);
    }

    private void migrateSettings() {
        RemoteSharedPreference remoteSharedPreference = RemoteSharedPreference.getInstance();
        if (remoteSharedPreference.contains(SPConstant.KEY_ALTITUDE_SOURCE)) {
            remoteSharedPreference.setValue(SPConstant.KEY_ALTITUDE_SOURCE_V2,
                    String.valueOf(remoteSharedPreference.getInt(SPConstant.KEY_ALTITUDE_SOURCE, 0)));
        }
        if (remoteSharedPreference.contains(SPConstant.KEY_ALTITUDE_ADJUST_VALUE)) {
            remoteSharedPreference.setValue(SPConstant.KEY_ALTITUDE_ADJUST_VALUE_V2,
                    String.valueOf(remoteSharedPreference.getInt(SPConstant.KEY_ALTITUDE_ADJUST_VALUE, 0)));
        }
        if (SharedManager.getInstance().contains(SPConstant.KEY_SPORT_MESSAGE_ENABLE)) {
            remoteSharedPreference.setValue(SPConstant.KEY_SPORT_MESSAGE_ENABLE,
                    SharedManager.getInstance().getBoolean(SPConstant.KEY_SPORT_MESSAGE_ENABLE, false));
            SharedManager.getInstance().remove(SPConstant.KEY_SPORT_MESSAGE_ENABLE);
        }
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object obj) {
        RemoteSharedPreference.getInstance().setValue(preference.getKey(), obj);
        String key = preference.getKey();

        switch (key) {
            case SPConstant.KEY_ALTITUDE_ADJUST_VALUE_V2 -> preference.setSummary(obj.toString());
            case SPConstant.KEY_SPORT_MESSAGE_ENABLE -> {
                if (RemoteServiceManager.getInstance().isSporting()) {
                    Boolean bool = (Boolean) obj;
                    MessageUtil.triggerGetui(bool);
                    MessageUtil.triggerHuanXin(bool);
                }
            }
            case SPConstant.KEY_ALTITUDE_SOURCE_V2 -> {
                ListPreference listPreference = (ListPreference) preference;
                int findIndexOfValue = listPreference.findIndexOfValue(obj.toString());
                preference.setSummary(findIndexOfValue >= 0 ? listPreference.getEntries()[findIndexOfValue] : null);
            }
            case SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE -> {
                if (Build.VERSION.SDK_INT >= 23) {
                    if (!Settings.canDrawOverlays(getContext())) {
                        new BiciAlertDialogBuilder(getContext())
                                .setMessage("蓝行申请开启悬浮窗权限，开启悬浮窗可大大提高运动稳定性。也可在手机系统设置中开启。")
                                .setPositiveButton("好的", (dialogInterface, i) -> PermissionUtils.requestPermission((Activity) SettingMoreFragment.this.getContext(), z -> {
                                    if (!z) {
                                        Toast.makeText(SettingMoreFragment.this.getContext(),
                                                "未授权，如果无法开启悬浮窗，可到设置页面手动开启后台弹窗权限; 开启悬浮窗可大大提高稳定性", Toast.LENGTH_SHORT).show();
                                    } else {
                                        SettingMoreFragment.this.checkMiui();
                                    }
                                })).show();
                    } else if (obj instanceof Boolean) {
                        if (!(Boolean) obj) {
                            RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE, false);
                            if (findPreference(SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE) instanceof SwitchPreference) {
                                ((SwitchPreference) findPreference(SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE)).setChecked(false);
                            }
                        } else {
                            RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE, true);
                            if (findPreference(SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE) instanceof SwitchPreference) {
                                ((SwitchPreference) findPreference(SPConstant.KEY_SPORT_FLOAT_PIP_ENABLE)).setChecked(true);
                            }
                        }
                    }
                }
            }
            case SPConstant.KEY_LATLNT_SOURCE -> {
                String obj2 = obj.toString();
                SharedManager.getInstance().setLatlngValue(obj2);
                preference.setSummary(obj2);
            }
            default -> {}
        }
        return true;
    }

    public void checkMiui() {
        if (!RomUtil.check(RomUtil.ROM_MIUI) || StartInBackgroundPermissionUtil.canBackgroundStart(getContext().getApplicationContext())) {
            return;
        }
        Toast.makeText(getContext(), "无法唤起蓝行，可在手机系统设置中开启【后台弹出界面】权限", Toast.LENGTH_SHORT).show();
        MiuiUtils.applyMiuiPermission(getContext().getApplicationContext());
    }
}